<script setup lang="ts">
import {useRolesStore} from "@/store/rolesStroe.ts";
import {ElNotification, ElTree, FormInstance} from 'element-plus'
import {getRoleByID, updateRole} from "@/api/role";
import {filtrationMenuChildrenID} from "@/utils/util.ts";
import {reqRoleData} from "@/api/role/type.ts";


const treeRef = ref<InstanceType<typeof ElTree>>()
const loading = ref(false)
const editRoleFormRef = ref<FormInstance>()
const roleStore = useRolesStore();
const checkedKeys = ref<number[]>([])
const editRole = reactive<reqRoleData>({
  ID: roleStore.roleId,
  name: '',
  describe: '',
  isUsable: 1,
  menuIDs: [],

})
// 提交表单
const submitEdit = async (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      editRole.menuIDs.length = 0
      editRole.menuIDs.push(...treeRef.value!.getCheckedKeys(), ...treeRef.value!.getHalfCheckedKeys())
      const res = await updateRole(editRole)
      if (res.code === 200) {
        loading.value = false
        ElNotification({
          message: res.msg,
          type: 'success',
        })
        roleStore.openEdit = false
        await roleStore.getRoleListFun()
      } else {
        loading.value = false
        ElNotification({
          message: res.msg,
          type: 'error',
        })
      }
    } else {
      loading.value = false
      console.log('error submit!', fields)
    }
  })
}
// 表单验证规则
const rules = reactive({
  name: [
    {required: true, message: '请输入角色名称', trigger: 'blur'},
  ],
  describe: [
    {required: true, message: '请输入角色描述', trigger: 'blur'},
  ]
})

onBeforeMount(() => {
  getRoleByID(roleStore.roleId).then((res) => {
    if (res.code === 200) {
      editRole.name = res.data.name
      editRole.describe = res.data.describe
      editRole.isUsable = res.data.isUsable
      if (res.data.Menus) {
        checkedKeys.value = filtrationMenuChildrenID(res.data.Menus)
      }
    } else {
      ElNotification({
        message: res.msg,
        type: 'error',
      })
    }
  })
})

// 自定义节点渲染函数
// const renderContent = (h: any, {data}: any) => {
//   // 拼接节点名称和提示信息
//   const label = data.name;
//   let suffix = '';
//   if (data.type === 1) {
//     suffix = '菜单';
//   }
//   if (data.type === 2) {
//     suffix = 'API';
//   }
//   // 返回一个包含节点名称和提示信息的 span 元素
//   return h('span', {
//         class: 'custom-tree-node', // 添加一个类名以便在CSS中定义样式
//       },
//       h('span', null, label),
//       h('span', {
//         style: {
//           color: "#009dff", // 设置提示信息字体颜色
//         }
//       }, suffix));
// };

</script>

<template>
  <div>
    <el-drawer v-model="roleStore.openEdit" title="编辑角色">
      <el-form :model="editRole" ref="editRoleFormRef" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editRole.name"/>
        </el-form-item>
        <el-form-item label="角色描述" prop="describe">
          <el-input v-model="editRole.describe"/>
        </el-form-item>
        <el-form-item label="角色状态">
          <el-radio v-model="editRole.isUsable" :label="1">启用</el-radio>
          <el-radio v-model="editRole.isUsable" :label="0">禁用</el-radio>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree style="width: 100%"
                   ref="treeRef"
                   :data="roleStore.menuList"
                   show-checkbox
                   node-key="ID"
                   :default-expanded-keys="[1, 2]"
                   :default-checked-keys="checkedKeys"
                   :props="{
              label: 'name',
              children: 'children',
            }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="roleStore.openEdit = false">取消</el-button>
          <el-button type="primary" @click="submitEdit(editRoleFormRef)" :loading="loading">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss">
.buttons-right {
  display: flex;
  justify-content: flex-end;
  /* 根据需要，您还可以添加其他样式，比如间距 */
  gap: 8px; /* 使用 gap 属性添加按钮之间的间距（请注意，gap 属性在旧版浏览器中可能需要前缀或使用其他方法实现）*/
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>